package com.edu.boot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.boot.config.UserContext;
import com.edu.boot.entity.*;
import com.edu.boot.service.CommunityCommentService;
import com.edu.boot.service.CommunityImagesService;
import com.edu.boot.service.CommunityService;
import com.edu.boot.mapper.CommunityMapper;
import com.edu.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Janson
* @description 针对表【community(社区帖子功能表)】的数据库操作Service实现
* @createDate 2025-04-12 19:10:49
*/
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community>
    implements CommunityService{
    @Autowired
    private CommunityImagesService communityImagesService;
    @Autowired
    CommunityMapper communityMapper;
    
    @Autowired
    UserService userService;
    @Autowired
    CommunityCommentService communityCommentService;
    /**
     * 多个表插入数据添加回滚，
     * @param community
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCommunity(Community community) {
        community.setCreateTime(DateUtil.date());
        community.setUid(UserContext.getUserId());
        communityMapper.insert(community);
        if(CollectionUtil.isNotEmpty(community.getImages())){
            List<CommunityImages> communityImagesList = community.getImages()
                    .stream()
                    .map(item -> {
                        CommunityImages communityImages = new CommunityImages();
                        communityImages.setCommunityId(community.getId());
                        communityImages.setImage(item);
                        communityImages.setCreateTime(DateUtil.date());
                        return communityImages;
                    })
                    .collect(Collectors.toList());
            communityImagesService.saveBatch(communityImagesList);
        }
    }
    
    @Override
    public IPage<Community> getList(Integer page, Integer pageSize) {
        Page<Community> pageCur = new Page<>(page, pageSize);
        IPage<Community> communityListPage = communityMapper.getCommunityListPage(pageCur);
        if(CollectionUtil.isNotEmpty(communityListPage.getRecords())){
            List<CommunityComment> commentList = communityCommentService.list();
            Map<Integer, List<CommunityComment>> commentMap = commentList.stream()
                    .collect(Collectors.groupingBy(
                            CommunityComment::getCommunityId,
                            Collectors.toList()
                    ));
            communityListPage.getRecords().forEach(item -> {
                item.setCommentNum(CollectionUtil.isNotEmpty(commentMap.get(item.getId())) ?
                                   commentMap.get(item.getId()).size() : 0);
            });
        }
        return communityListPage;
    }
    
    @Override
    public Community getCommunity(Integer id) {
        Community community = communityMapper.getCommunity(id);
    
        // 更新浏览量
        Community addClick = new Community();
        addClick.setId(id);
        addClick.setClickNum(community.getClickNum() + 1);
        communityMapper.updateById(addClick);
    
        Map<Integer, Users> userMap = userService.getUserObjMap();
    
        // 获取所有评论
        LambdaQueryWrapper<CommunityComment> queryWrapper = new LambdaQueryWrapper<CommunityComment>()
                .eq(CommunityComment::getCommunityId, id);
        List<CommunityComment> commentList = communityCommentService.list(queryWrapper);
    
        // 设置用户信息
        commentList.forEach(comment -> {
            Users user = userMap.get(comment.getUid());
            comment.setNickname(user != null ? user.getNickname() : "");
            comment.setImageData(user != null ? user.getImageData() : "");
        });
    
        // 构建 ID -> 评论的映射
        Map<Integer, CommunityComment> commentMap = commentList.stream()
                .collect(Collectors.toMap(CommunityComment::getId, c -> c));
    
        // 构建父子结构
        List<CommunityComment> rootComments = new ArrayList<>();
        for (CommunityComment comment : commentList) {
            Integer parentId = comment.getParentId();
            if (parentId == null) {
                // 顶级评论
                rootComments.add(comment);
            } else {
                CommunityComment parent = commentMap.get(parentId);
                if (parent != null) {
                    if (parent.getReplies() == null) {
                        parent.setReplies(new ArrayList<>());
                    }
                    parent.getReplies().add(comment);
                }
            }
        }
    
        community.setComments(rootComments);
        community.setCommentNum(commentList.size());
        return community;
    }
    
}




